package LeetCode.month02.day54;

public class No112 {
    int sum = 0;
    public boolean hasPathSum(TreeNode root, int targetSum) {
        if(root==null) return false;
        if(root.left == null&&root.right == null){
            sum+=root.val;
            if(targetSum==sum) return true;
            sum-=root.val;
            return false;
        }
        sum+=root.val;
        if(hasPathSum(root.left,targetSum)) return true;
        if(hasPathSum(root.right,targetSum)) return true;
        sum-=root.val;
        return false;
    }

    public boolean haspathSum(TreeNode root,int targetSum){
        if (root == null) return false;

        // 如果是叶子节点，检查剩余值是否等于当前节点值
        if (root.left == null && root.right == null) {
            return targetSum == root.val;
        }

        // 递归检查左右子树，用目标值减去当前节点值
        int remaining = targetSum - root.val;
        return hasPathSum(root.left, remaining) ||
                hasPathSum(root.right, remaining);
    }
}
